﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Marmat.Data
{
    public class ViewRowHelper
    {
        public string TableName { get; set; }
        public Suffix Suffix { get; set; }
        public string Identify { get; set; }

        public List<Column> PrimaryKey
        {
            get
            {
                if (this.m_PrimaryKey is null)
                {
                    this.m_PrimaryKey = new List<Column>();
                }

                return this.m_PrimaryKey;
            }
        }

        private List<Column> m_PrimaryKey;

        public string GetSaveString(DataTable dt, DataRow dr)
        {
            var Columns = new List<Column>();
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.AutoIncrement == false)
                {
                    var Item = new Column();
                    Item.DataColumn = dc.ColumnName;
                    Item.ViewColumn = dc.ColumnName;
                    Columns.Add(Item);
                }
            }

            return this.GetSaveString(dt, dr, Columns.ToArray());
        }

        public bool Save(BaseConnection Connection, DataTable dt, DataRow dr, Column[] Columns)
        {
            bool Result = false;
            var cmd = new SQLCommand(Connection);
            cmd.CommandText = this.GetSaveString(dt, dr, Columns);
            if (!string.IsNullOrEmpty(this.Identify))
            {
                cmd.CommandText += "\r\nSELECT @@IDENTITY";
                int Identify = Convert.ToInt32(cmd.ExecuteScalar());
                dr[this.Identify] = Identify;
            }
            else
            {
                Result = cmd.ExecuteNonQuery() > 0;
            }

            return Result;
        }

        public string GetSaveString(DataTable dt, DataRow dr, Column[] Columns)
        {
            string Result = null;
            var Helper = new SQLBaseHelper();
            Helper.TableName = this.TableName;
            switch (dr.RowState)
            {
                case DataRowState.Added:
                    {
                        // 添加主键==================================================
                        foreach (Column Column in this.PrimaryKey)
                        {
                            var dc = dt.Columns[Column.ViewColumn];
                            var Current = dr[Column.ViewColumn, DataRowVersion.Current];
                            Helper.PrimaryKey.Add(Column.DataColumn, dc.DataType, Current);
                        }

                        foreach (Column Column in Columns)
                        {
                            var dc = dt.Columns[Column.ViewColumn];
                            if (dc.AutoIncrement == false && !ReferenceEquals(dr[dc], DBNull.Value) && dr[dc] is object) // 如果当前列不是自增列并且不为空的话
                            {
                                Helper.Columns.Add(Column.DataColumn, dc.DataType, dr[dc]);
                            }
                        }

                        Result = Helper.GetSqlString(SQLBaseHelper.ModeEnum.Added);
                        break;
                    }

                case DataRowState.Modified:
                    {
                        // 添加主键==================================================
                        foreach (Column Column in this.PrimaryKey)
                        {
                            var dc = dt.Columns[Column.ViewColumn];
                            var Current = dr[Column.ViewColumn, DataRowVersion.Current];
                            var Original = dr[Column.ViewColumn, DataRowVersion.Original];
                            if (!Current.Equals(Original))
                            {
                                Helper.PrimaryKey.Add(Column.DataColumn, dc.DataType, Original);
                            }
                            else
                            {
                                Helper.PrimaryKey.Add(Column.DataColumn, dc.DataType, Current);
                            }
                        }

                        foreach (Column Column in Columns)
                        {
                            var Current = dr[Column.ViewColumn, DataRowVersion.Current];
                            var Original = dr[Column.ViewColumn, DataRowVersion.Original];
                            if (!Current.Equals(Original))
                            {
                                var dc = dt.Columns[Column.ViewColumn];
                                Helper.Columns.Add(Column.DataColumn, dc.DataType, Current);
                            }
                        }

                        if (Helper.Columns.Count > 0)
                        {
                            Result = Helper.GetSqlString(SQLBaseHelper.ModeEnum.Modified);
                        }

                        break;
                    }

                case DataRowState.Deleted:
                    {
                        // 添加主键==================================================
                        foreach (Column Column in this.PrimaryKey)
                        {
                            var dc = dt.Columns[Column.ViewColumn];
                            var Original = dr[Column.ViewColumn, DataRowVersion.Original];
                            Helper.PrimaryKey.Add(Column.DataColumn, dc.DataType, Original);
                        }

                        Result = Helper.GetSqlString(SQLBaseHelper.ModeEnum.Deleted);
                        break;
                    }
            }

            return Result;
        }

        /// <summary>
        /// 获取保存时单元格的值(SQL用)
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="ColumnName"></param>
        /// <param name="DataRowVersion"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string GetCellValue(DataRow dr, string ColumnName, DataRowVersion DataRowVersion)
        {
            return GetCellValue(dr, ColumnName, DataRowVersion, null);
        }

        /// <summary>
        /// 获取保存时单元格的值(SQL用)
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="ColumnName"></param>
        /// <param name="DataRowVersion"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string GetCellValue(DataRow dr, string ColumnName, DataRowVersion DataRowVersion, Suffix Suffix)
        {
            if (Suffix is null)
            {
                Suffix = new Suffix();
            }

            var dc = dr.Table.Columns[ColumnName];
            var obj = dr[ColumnName, DataRowVersion];
            return GetCellValue(dc.DataType, obj, dc.MaxLength, Suffix);
        }

        /// <summary>
        /// 获取保存时单元格的值(SQL用)
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string GetCellValue(Type DataType, object Obj, int MaxLength, Suffix Suffix)
        {
            return SQLBaseHelper.GetSqlValue(DataType, Obj, MaxLength, Suffix);
        }

        public class Column
        {

            /// <summary>
            /// 前台表对应的列
            /// </summary>
            /// <value></value>
            /// <returns></returns>
            /// <remarks></remarks>
            public string ViewColumn
            {
                get
                {
                    return this._ViewColumn;
                }

                set
                {
                    this._ViewColumn = value;
                }
            }

            private string _ViewColumn;

            /// <summary>
            /// 后台表对应的列
            /// </summary>
            /// <value></value>
            /// <returns></returns>
            /// <remarks></remarks>
            public string DataColumn
            {
                get
                {
                    if (string.IsNullOrEmpty(this._DataColumn))
                    {
                        return this.ViewColumn;
                    }

                    return this._DataColumn;
                }

                set
                {
                    this._DataColumn = value;
                }
            }

            private string _DataColumn;

            public void ResetViewColumn()
            {
                this.ViewColumn = null;
            }

            protected bool ShouldSerializeViewColumn()
            {
                return !string.IsNullOrEmpty(this._ViewColumn);
            }

            public void ResetDataColumn()
            {
                this.DataColumn = null;
            }

            protected bool ShouldSerializeDataColumn()
            {
                return !string.IsNullOrEmpty(this._DataColumn);
            }

            public override string ToString()
            {
                string result = base.ToString();
                if (!string.IsNullOrEmpty(this._ViewColumn))
                    result = $"ViewColumn=\"{this.ViewColumn}\"";
                if (!string.IsNullOrEmpty(this._DataColumn))
                    result += (!string.IsNullOrEmpty(result) ? "," : "") + $"DataColumn=\"{this.DataColumn}\"";
                return result;
            }
        }
    }
}